<?php
/**
 * Created by PhpStorm.
 * User: 55371
 * Date: 2017/10/21
 * Time: 15:00
 */

namespace App\Http\Controllers\Api\Order;

use Carbon\Carbon;

use App\Service\CartService;

use App\Models\Bill\Bill;  //订单主表

use App\Models\ConfigureFunction; //功能配置表

use App\Models\Mall\MallMaster; //购物中心表

use App\Models\Activity\ActivityCommonMall; //交易类活动可参与的门店表

use App\Models\Card\CardCoupon; //卡券表

use App\Models\Customer\Customer;

use Illuminate\Http\Request;

use App\Http\Controllers\Controller;

use Illuminate\Support\Facades\Redis as Redis;

use App\Service\Order\GeneralOrderService;

use App\Service\Pay\WxPayService;

use App\Service\WdhService;

class BillSubmitController extends Controller
{

    public function billSubmit( Request $request )
    {

        $session_id = $request->input('session_id', session_id());
        $platform = $request->input('platform', 6);
        $act = $request->input('act');
        $latitude = $request->input('latitude');
        $longitude = $request->input('longitude');
        $mobile = $request->input('mobile');
        $name = $request->input('name');
        $payPwd = $request->input('payPwd');
        $send_time = $request->input('send_time');
        $pickup_start_time = $request->input('pickup_start_time');
        $pickup_end_time = $request->input('pickup_end_time');
        $remark = $request->input('remark');
        $datetime = Carbon::now();
        $host = $request->getSchemeAndHttpHost();

        if (empty($session_id)) {
            return response()->json(['code' => 100001, 'message' => '缺少参数：session_id']);
        }

        $pcustID = get_customer_id($session_id, $platform);
        if (!$pcustID) {
            return response()->json(['code' => 100002, 'message' => '请登录']);
        }

        //查询会员信息
        $customer = Customer::select('pcustID', 'custID', 'cardNo')->find($pcustID);
        if (!$customer) {
            return response()->json(['code' => 100003, 'message' => '会员信息不存在']);
        }

        //获取openId
        $openId = '';
        $customer_redis = json_decode(app('redis')->get('WX_APPLET_USER_' . $session_id), true);
        if (isset($customer_redis['openId']) && !empty($customer_redis['openId'])) {
            $openId = $customer_redis['openId'];
        }

        $bill_array['host'] = $host;
        $bill_array['openId'] = $openId;
        $bill_array['cardNo'] = $customer->cardNo;

        /**
         * ===================================
         * 获取购物车数据
         * ===================================
         */
        $bill_array = CartService::getCartInfo( $act, $pcustID );

        //是否开启选店
        $shop_select_mall = ConfigureFunction::getConfigure(8);
        $bill_array['is_shop_select_mall'] = $shop_select_mall['is_open_choose_mall'];

        //如果是微信交易类活动，关闭选店模式
        if (in_array($_REQUEST['act'], array('special', 'flash', 'crowd'))) {
            $bill_array['is_shop_select_mall'] = 0;
        }

        $virtual_id = 0;

        if (isset($bill_array['goods']['general']) && !empty($bill_array['goods']['general'])) {
            foreach($bill_array['goods']['general'] as $general) {
                if (ebsig_is_int($general['virtual_id'])) {
                    $virtual_id = 1;
                }
            }
        }

        if (isset($bill_array['goods']['points']) && !empty($bill_array['goods']['points'])) {
            foreach($bill_array['goods']['points'] as $points) {
                if (ebsig_is_int($points['virtual_id'])) {
                    $virtual_id = 1;
                }
            }
        }

        $bill_array['send_limit_money'] = 0;
        $bill_array['send_limit_points'] = 0;

        if ($bill_array['is_shop_select_mall'] == 1) {

            $cust_mall_data  = json_decode(Redis::get('CHECKOUT_ACTIVITY_MALL_' . $pcustID), true);
            if ( !$cust_mall_data ) {
                return response()->json(['code' => 100000, 'message' => '请先绑定门店']);
            }

            $mall_result = MallMaster::select('mallName','mallCode','provinceName','cityName','countyName','address','phone','mobile','useFlg')->where('mallID',$bill_array['mallID'])->first();
            if ( $mall_result ) {
                $mall_result = collect($mall_result)->toArray();
                if ( $mall_result['useFlg'] == 0 ) {
                    return response()->json(['code' => 1000001, 'message' => '门店已禁用']);
                }
            }else{
                return response()->json(['code' => 1000001, 'message' => '门店已不存在']);
            }

            if( $bill_array['master']['sendTypeID'] == 1 ){  //当前选择送货上门
                $bill_array['send_limit_money'] = $cust_mall_data['send_limit_money'];
                $bill_array['send_limit_points'] = $cust_mall_data['send_limit_points'];
                $bill_array['master']['mallID'] = $cust_mall_data['mallID'];
                $bill_array['master']['mallName'] = $cust_mall_data['mallName'];
                $bill_array['master']['mallCode'] = $cust_mall_data['mallCode'];

                if ( $cust_mall_data['mallType'] == 1 ) {
                    $mallID = $cust_mall_data['mallID'];
                } else {
                    $mallID = $cust_mall_data['zt_id'];
                }

                /**
                 * 检查门店配送范围
                 */
                $result_array = WdhService::checktrictSendRange(array('mallID' => $mallID, 'longitude' => $longitude, 'latitude' => $latitude));
                if ($result_array['code'] != 200) {
                    return response()->json(['code' => $result_array['code'], 'message' => $result_array['message']]);
                }
            }

            $bill_array['master']['mallID']   = $cust_mall_data['mallID'];
            $bill_array['master']['mallName'] = $cust_mall_data['mallName'];
            $bill_array['master']['mallCode'] = $cust_mall_data['mallCode'];

        }

        //如果是活动订单又是指定门店，检查活动门店情况
        if (isset($bill_array['activity_id']) && ebsig_is_int($bill_array['activity_id'])) {
            $mall_array = ActivityCommonMall::where('activity_id', $bill_array['activity_id'])->get(['mall_code'])->toArray();

            if ($mall_array) {
                $mall_array = ActivityCommonMall::where('activity_id', $bill_array['activity_id'])
                    ->where('mall_id' , $bill_array['master']['mallID'])->get(['mall_code'])->toArray();
                if (!$mall_array) {
                    return response()->json(['code' => 400, 'message' => '['.$bill_array['master']['mallName'].']不参与本次活动']);
                }
            }
        }

        //获取订单配置
        $bill_configure = ConfigureFunction::getConfigure(21);
        $bill_create_pickup_code = $bill_configure['bill_create_pickup_code'];

        //获取卡券设置（是否有supr：1有，0无）
        $card_configure = ConfigureFunction::getConfigure(45);
        $is_sync_third_erp = $card_configure['is_sync_third_erp'];

        /**
         * 普通订单、按商品生码、门店自提且存在spur接口，则校验订单商品是否存在对应的提货券码
         */
        if( $bill_array['master']['billType'] == 1 && $bill_array['master']['sendTypeID'] == 2 && $bill_create_pickup_code == 2 && $is_sync_third_erp == 1 ){

            foreach ( $bill_array['goods']['general'] as $goods ){

                //提货券剩余券码数量
                $left_total = 0;

                //查询未过期且还有码子的电子券
                $eticket_data = CardCoupon::select('total_num', 'getNum')->where([
                            ['useFlg', '=', 1],
                            ['postID', '=', $goods['postID']],
                            ['total_num', '>', 'getNum' ],
                            ['create_code_stat', '=', 1]
                        ])
                        ->where(['use_end_time' => $datetime])
                        ->orWhere(['time_type' => 2])
                        ->orderBy('card_id', 'ASC')->get()->toArray();

                if( empty($eticket_data) ){
                    return response()->json(['code' => 400, 'message' => '生成提货券失败']);
                }

                foreach ( $eticket_data as $eticket ){
                    $left_total += $eticket['total_num'] - $eticket['getNum'];
                    if( $left_total > $goods['goods_amount'] ){
                        break;
                    }
                }

                if( $left_total < $goods['goods_amount'] ){
                    return response()->json(['code' => 400, 'message' => '生成提货券失败']);
                }

            }

        }

        if( $bill_array['bill_config_id'] != 2 ){ //普通订单才去校验配送方式

            if( $virtual_id == 0 ){
                //配送方式
                if (!isset($bill_array['master']['sendTypeID']) || empty($bill_array['master']['sendTypeID'])) {
                    return response()->json(['code' => 400, 'message' => '请选择配送方式']);
                }
                if (!isset($bill_array['master']['deliverid']) || empty($bill_array['master']['deliverid'])) {
                    return response()->json(['code' => 400, 'message' => '请选择收货地址']);
                }
                if ($bill_array['master']['ziti'] == 1 && isset($mobile) && is_mobile($mobile)) {
                    $bill_array['master']['deliver_mobile'] = $mobile;
                }
                if ($bill_array['master']['ziti'] == 1 && !empty($name)) {
                    $bill_array['master']['deliver_name'] = $name;
                }
            } else {
                $bill_array['master']['sendTypeID']   = 0;
                $bill_array['master']['sendTypeName'] = '';
            }

        }

        if ($bill_array['master']['ziti'] == 1) {

            //查询自提时间设置
            $ztTimeArray = ConfigureFunction::getConfigure(13);

            //查询自提时间设置
            $shopTypeConfigure = ConfigureFunction::getConfigure(43);

            $tip = $shopTypeConfigure['shop_type'] == 1 ? '送货' : '提货';

            if ( isset($ztTimeArray['detail'][0]) ) {

                //提货时间
                if (!isset($pickup_start_time) || empty($pickup_start_time) || !isset($pickup_end_time) || empty($pickup_end_time)) {
                    return response()->json(['code' => 400, 'message' => '请选择' . $tip . '时间']);
                }
                if (!is_date($pickup_start_time) || !is_date($pickup_end_time)) {
                    return response()->json(['code' => 400, 'message' => $tip . '时间格式不正确']);
                }
                if ( $shopTypeConfigure['shop_type']  != 1 && $datetime > $pickup_end_time ) {
                    return response()->json(['code' => 400, 'message' => $tip . '时间不能小于当前时间']);
                }

            } else if ( !in_array( $bill_array['billType'] , array(2,3,7) ) ) {
                $pickup_start_time = $datetime;
                $pickup_end_time = date('Y-m-d H:i:s',strtotime('+365 day'));
            }

        } else {

            //配送方式为送货上门
            if( empty($pickup_start_time) || empty($pickup_end_time) ){
                $pickup_start_time = $datetime;
                $pickup_end_time = date('Y-m-d H:i:s',strtotime('+365 day'));
            } else {
                $pickup_start_time = trim($pickup_start_time);
                $pickup_end_time = trim($pickup_end_time);
            }

        }

        if (isset($send_time) && !empty($send_time)) {
            $pickup_start_time = null;
            $pickup_end_time = null;
        } else {
            $send_time = null;
        }

        //提货时间
        $bill_array['master']['pickup_start_time'] = trim($pickup_start_time);
        $bill_array['master']['pickup_end_time'] = trim($pickup_end_time);
        $bill_array['master']['send_time'] = trim($send_time);

        //支付方式
        if (!isset($bill_array['master']['payTypeID']) || empty($bill_array['master']['payTypeID'])) {
            return response()->json(['code' => 400, 'message' => '请选择支付方式']);
        }

        //支付密码
        if (!isset($payPwd) || empty($payPwd)) {
            $payPwd = null;
        }

        $bill_array['master']['payPwd'] = $payPwd;

        //订单留言
        if ( isset($remark) && !empty($remark) ) {
            $bill_array['master']['remark'] = convertVar($remark);
        }

        //订单平台
        $bill_array['master']['billPlatform'] = $platform;

        //订单渠道
        $bill_array['master']['billChannel'] = 15;

        //会员
        $bill_array['pcustID'] = $pcustID;
        $bill_array['custID'] = $customer->custID;

        //实例化团购订单类
        $pt_order_service = new GeneralOrderService($bill_array);

        //新增订单
        $res = $pt_order_service->submit();

        if ( $res['code'] != 200 ) {
            return response()->json(['code' => $res['code'], 'message' => $res['message']]);
        }

        $bill_no = $res['data']['bill_no'];
        $parent_bill_no = $res['data']['parent_bill_no'];
        $pay_amount = $res['data']['pay_amount'];
        $mallID = $res['data']['mallID'];
        $pay_status = $res['data']['pay_status'];

        $return_data = array(
            'bill_no' => $bill_no,
            'parent_bill_no' => $parent_bill_no,
            'payTypeID' => 50,
            'pay_status' => $pay_status,
            'pay' => []
        );

        if( $pay_status == 1 ){
            return response()->json(['code' => 200, 'message' => 'ok', 'data' => $return_data]);
        }

        $trade_type = '';
        $wx_config_seeting = ConfigureFunction::getConfigureField(41,'wechat_type');
        if ( $wx_config_seeting == 1) {
            $trade_type = 'JSAPI';
        }
        if ( $wx_config_seeting != 1 ) {
            $trade_type = 'NATIVE';
        }

        //微信异步接收路径$host
        $notify_url = $host . '/onlinepay/weixin/notify';

        $params = [
            'out_trade_no' => $bill_no,
            'trade_type' => $trade_type,
            'payTypeID' => 50,
            'mallID' => $mallID,
            'body' => '微商城',
            'total_fee' => $pay_amount,
            'pcustID' => $pcustID,
            'type' => 4,
            'openId' => $res['data']['openId'],
            'notify_url' => $notify_url
        ];

        $WxPayService = new WxPayService($params);

        $wx_pay = $WxPayService->request();
        if ($wx_pay['code'] == 200) {
            $return_data['pay'] = $wx_pay['data'];
        }

        return response()->json(['code' => 200, 'message' => 'ok', 'data' => $return_data]);

    }
}